using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace ProjectCodeS.Models
{ 
    public class ItemRepository : IItemRepository
    {
        ProjectCodeSContext context = new ProjectCodeSContext();

        public IQueryable<Item> All
        {
            get { return context.Items; }
        }

        public IQueryable<Item> AllIncluding(params Expression<Func<Item, object>>[] includeProperties)
        {
            IQueryable<Item> query = context.Items;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Item Find(int id)
        {
            return context.Items.Find(id);
        }

        public void InsertOrUpdate(Item item)
        {
            if (item.Id == default(int)) {
                // New entity
                context.Items.Add(item);
            } else {
                // Existing entity
                context.Entry(item).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var item = context.Items.Find(id);
            context.Items.Remove(item);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }

    public interface IItemRepository : IDisposable
    {
        IQueryable<Item> All { get; }
        IQueryable<Item> AllIncluding(params Expression<Func<Item, object>>[] includeProperties);
        Item Find(int id);
        void InsertOrUpdate(Item item);
        void Delete(int id);
        void Save();
    }
}